﻿#include "plotWidget.h"
#include <QtWidgets/QColorDialog>
#include "qFlowLayout.h"
#include "app.h"

//构造函数
PlotWidget::PlotWidget(QSettings *settings):
	_numberDisplay(true),
	_settings(settings){
	//加上这一句才会自动释放对象
	this->setAttribute(Qt::WA_DeleteOnClose);
	ui.setupUi(this);

	//初始化QtAwesome
	QtAwesome* awesome = new QtAwesome();
	awesome->initFontAwesome();
	QVariantMap options;
	//初始化颜色
	options.insert("color", QColor(0x94ffff));
	options.insert("color-active", QColor(0x94ffff));
	//按键添加图标
	ui.clearButton->setIcon(awesome->icon(fa::eraser, options));
	ui.allDisplayButton->setIcon(awesome->icon(fa::expand, options));
	ui.btnSelectAll->setIcon(awesome->icon(fa::checksquare, options));
	ui.btnSelectNone->setIcon(awesome->icon(fa::squareo, options));
	ui.readCurvesFilesBtn->setIcon(awesome->icon(fa::folderopeno, options));
	ui.saveCurvesFilesBtn->setIcon(awesome->icon(fa::paste, options));
	ui.showSwitchButton->setCheckable(true);
	options.insert("text-off", QString(fa::eyeslash));
	ui.showSwitchButton->setIcon(awesome->icon(fa::eye, options));

	//导入配置
	ui.settingTable->initState(_settings);

	curves = ui.curvesWidget;
	//遍历settingTable的初始数据
	int curvesCnt = ui.settingTable->rowCount();
	for (int i = 0; i < curvesCnt; i++) {
		QWidget *selectWidget = ui.settingTable->cellWidget(i, 0);
		QCheckBox *checkBox = selectWidget->findChild<QCheckBox*>(QString("checkBox_%1").arg(i));
		QEditableLable *editableLable = selectWidget->findChild<QEditableLable*>(QString("editableLable_%1").arg(i));

		GraphData *graph = &(*curves->getGraphRecord())[i];
		graph->graphIndex = (uint8_t)i;
		graph->isShow = checkBox->isChecked();
		graph->name = editableLable->curveName;
		graph->color = editableLable->curveColor;
		connect(checkBox, SIGNAL(clicked(bool)), this, SLOT(selectShowChange(bool)));
		connect(editableLable, SIGNAL(colorChanged(QColor)), this, SLOT(curveColorChanged(QColor)));
		connect(editableLable, SIGNAL(nameChanged(QString)), this, SLOT(curveNameChanged(QString)));
		ui.tracerComboBox->addItem(graph->name);
		ui.tracerComboBox->setItemWidth(80);
	}
	curves->modifyCurves();

	//对x轴范围变化设置回调
	connect(curves->xAxis, SIGNAL(rangeChanged(QCPRange)), this, SLOT(xAxisCangeCallBack(QCPRange)));
	connect(ui.settingTable, SIGNAL(itemSelectionChanged()), this, SLOT(traceTargetChanged()));
	connect(ui.clearButton, SIGNAL(clicked()), curves, SLOT(clearAllData()));
	connect(this, SIGNAL(clearCurves()), curves, SLOT(clearAllData()));
	connect(ui.allDisplayButton, SIGNAL(clicked()), curves, SLOT(showAllGraph()));
	//滚动条设置
	ui.curvesScrollBar->setValue(0);
	ui.curvesScrollBar->setSingleStep(1);
	ui.curvesScrollBar->setPageStep(curves->xAxis->range().size());
	connect(ui.curvesScrollBar, SIGNAL(sliderMoved(int)), this, SLOT(curvesScrollBarChanged(int)));
	connect(ui.curvesScrollBar, SIGNAL(actionTriggered(int)), this, SLOT(curvesScrollBarAction(int)));//actionTriggered传递的int类型貌似是内部action的序号
	connect(curves, SIGNAL(autoRangeAdjusted(QCPRange)), this, SLOT(curvesXAxisChanged(QCPRange)));

	//启动定时器，用于添加数据，100Hz
	startTimer(10, Qt::PreciseTimer);
}

PlotWidget::~PlotWidget() {

}

void PlotWidget::setCurvesReload(bool enable) {
	if (enable) {
		curves->reloadBasicKey();
	}
}

void PlotWidget::closeEvent(QCloseEvent * event) {
	qDebug() << "close plotwidget.";
}

//曲线颜色变化 slot
void PlotWidget::curveColorChanged(QColor color) {
	QString objName = sender()->objectName();
	QRegExp rx(QString("editableLable_(.*)"));
	objName.indexOf(rx);
	uint16_t index = rx.cap(1).toUInt();

	GraphData *graph = &(*curves->getGraphRecord())[index];
	graph->color = color;
	//当前曲线在显示的情况下对showCurves刷新
	if (graph->isShow) {
		curves->modifyCurves();
	}

	//QT写入ini配置文件
	_settings->beginGroup("Curves");
	_settings->setValue(QString("color_%1").arg(index), QVariant(color.rgba()));
	_settings->endGroup();
}

//曲线名称变化 slot
void PlotWidget::curveNameChanged(QString name) {
	QString objName = sender()->objectName();
	QRegExp rx(QString("editableLable_(.*)"));
	objName.indexOf(rx);
	uint16_t index = rx.cap(1).toUInt();

	GraphData *graph = &(*curves->getGraphRecord())[index];
	graph->name = name;
	//当前曲线在显示的情况下对showCurves刷新
	if (graph->isShow) {
		curves->modifyCurves();
	}

	//qt写入ini配置文件
	_settings->beginGroup("Curves");
	_settings->setValue(QString("name_%1").arg(index), name);
	_settings->endGroup();
}

//曲线选择显示 Slot
void PlotWidget::selectShowChange(bool checked) {
	QString name = sender()->objectName();
	QRegExp rx(QString("checkBox_(.*)"));
	name.indexOf(rx);
	uint16_t index = rx.cap(1).toUInt();

	GraphData *graph = &(*curves->getGraphRecord())[index];
	graph->isShow = checked;
	curves->modifyCurves();

	//qt写入ini配置文件
	_settings->beginGroup("Curves");
	_settings->setValue(QString("check_%1").arg(index), checked);
	_settings->endGroup();
}

//点击的列改变
void PlotWidget::traceTargetChanged() {
	int selectTrace =  ui.settingTable->currentRow();
	curves->setTraceGraph(selectTrace);
	ui.tracerComboBox->setCurrentIndex(selectTrace);
}

//添加数据
void PlotWidget::timerEvent(QTimerEvent *event) {
	Q_UNUSED(event)

	static int loops = 0;
	//使用临时变量，防止锁太长的时间
	QVector<SensorCache> temporaryCache;
	//线程锁
	App::curvesMutex.lock();
	if (App::sensorCurveCache.count() > 0) {
		temporaryCache.append(App::sensorCurveCache);
		App::sensorCurveCache.clear();
	}
	App::curvesMutex.unlock();

	if (curves->reloadKey) {
		for (int i = 0; i < temporaryCache.count(); i++) {
			qDebug() << "-- " << temporaryCache[i].getCntr();
		}
	}

	while (temporaryCache.count() > 0) {
		curves->addData(temporaryCache.takeFirst());
	}
	//50Hz刷新一次
	if (!((loops++) % 2)) {
		//更新表格区的数值
		QVector<GraphData> *HistoryData = (QVector<GraphData> *)curves->getGraphRecord();
		if (_numberDisplay) {
			for (int i = 0; i < ui.settingTable->rowCount(); i++) {
				QLineEdit *numberLine = ui.settingTable->cellWidget(i, 2)->findChild<QLineEdit*>(QString("lineEdit_%1").arg(i));
				if ((*HistoryData)[i].valVec.size() > 0)
					numberLine->setText(QString::number((*HistoryData)[i].valVec.back()));
				else
					numberLine->setText("--");

				QLabel *lengthLabel = ui.settingTable->cellWidget(i, 1)->findChild<QLabel *>(QString("label_%1").arg(i));
				if ((*HistoryData)[i].valVec.size() > 0)
					lengthLabel->setText(QString("%1Byte").arg(QString::number((*HistoryData)[i].valueLength)));
				else
					numberLine->setText("--");
			}
		}
	}
}

//x轴显示范围设置
void PlotWidget::xAxisChangeRange() {
	curves->setXAxisRange((float)ui.xRangeSpinBox->value());
}

//x轴显示范围的回调显示函数
void PlotWidget::xAxisCangeCallBack(QCPRange range) {
	static int lastSize;
	int size = (int)range.size();
	if (size != lastSize) {
		ui.xRangeSpinBox->setValue(size);
	}
	lastSize = size;
}

//游标开关
void PlotWidget::tracerClicked(bool checked) {
	curves->setTracerEnable(checked);
}

//显示开关
void PlotWidget::showSwitch() {
	QPushButton *optBtn = qobject_cast<QPushButton *>(sender());
	if (optBtn->text() == QObject::tr("开启显示")) {
		optBtn->setText("关闭显示");
		curves->setUpdate(true);
		//重置basicKey的对比值
		curves->reloadBasicKey();
		emit operationRecord(fa::eye, tr("开启曲线显示"));
	}
	else {
		optBtn->setText("开启显示");
		curves->setUpdate(false);
		emit operationRecord(fa::eyeslash, tr("关闭曲线显示"));
	}
}

//取消全部选择
void PlotWidget::selectNone() {
	for (int i = 0; i < ui.settingTable->rowCount(); i++) {
		QWidget *selectWidget = ui.settingTable->cellWidget(i, 0);
		QCheckBox *checkBox = selectWidget->findChild<QCheckBox*>(QString("checkBox_%1").arg(i));
		if (!ui.settingTable->isRowHidden(i)) {
			checkBox->setChecked(false);
			GraphData *graph = &(*curves->getGraphRecord())[i];
			graph->isShow = checkBox->checkState();
		}
	}
	curves->modifyCurves();
}

//选择全部
void PlotWidget::selectAll() {
	for (int i = 0; i < ui.settingTable->rowCount(); i++) {
		QWidget *selectWidget = ui.settingTable->cellWidget(i, 0);
		QCheckBox *checkBox = selectWidget->findChild<QCheckBox*>(QString("checkBox_%1").arg(i));
		if (!ui.settingTable->isRowHidden(i)) {
			checkBox->setChecked(true);
			GraphData *graph = &(*curves->getGraphRecord())[i];
			graph->isShow = checkBox->checkState();
		}
	}
	curves->modifyCurves();
}

//搜索曲线
void PlotWidget::curvesSearch(const QString &text) {
	QRegExp re(text);
	for (int i = 0; i < ui.settingTable->rowCount(); i++) {
		bool passCondition;
		QWidget *selectWidget = ui.settingTable->cellWidget(i, 0);
		QEditableLable *editableLable = selectWidget->findChild<QEditableLable*>(QString("editableLable_%1").arg(i));
		if (re.indexIn(editableLable->curveName) < 0)//匹配失败
			passCondition = false;
		else
			passCondition = true;
		ui.settingTable->setRowHidden(i, !passCondition);
	}
}

//数值显示更新的开关
void PlotWidget::numberUpdate(bool checked) {
	_numberDisplay = checked;
}

//滚动条变化槽
void PlotWidget::curvesScrollBarChanged(int value) {
	float range = curves->xAxis->range().size();
	//如果手动拖动滑动条往左，则会自动取消掉自动跟随
	if (value + range < curves->stopBasicKey) {
		curves->setAutoScroll(false);
	}
	//手动拖动滚动条到最右侧则会开启自动跟随
	else {
		curves->setAutoScroll(true);
	}
	curves->xAxis->setRange(value , value + range);
	curves->replot(QCustomPlot::rpQueuedReplot);
}

void PlotWidget::curvesScrollBarAction(int value) {

}

//图标X轴变化槽
void PlotWidget::curvesXAxisChanged(QCPRange range) {
	ui.curvesScrollBar->setRange(0, qMax<int>(curves->getBasicKey() - range.size(), 1));
	ui.curvesScrollBar->setPageStep(qRound(range.size()));
	if (curves->isAutoScroll()) {
		ui.curvesScrollBar->setValue(qRound(curves->stopBasicKey));
	}
	else {
		if (curves->isMiddleMove()) {
			ui.curvesScrollBar->setValue(qRound(range.lower));
		}
	}
}

//曲线数据文件槽
void PlotWidget::fileOperation() {
	QPushButton *btn = (QPushButton *)sender();
	if (btn->objectName() == ui.readCurvesFilesBtn->objectName()) {
	
	}
	else if (btn->objectName() == ui.saveCurvesFilesBtn->objectName()) {
		//创建一个新窗口
		_curvesFiles = new CurvesFiles(curves->getGraphRecord());
		//模态弹出
		_curvesFiles->exec();
	}
}

